<!-- 部门树 -->
<template>
	
	<div class="pane" style="width: 280px;">
		<div class="head" style="align-items: center;display: flex;justify-content: space-between;">
			<span>接口分组</span>
			<div style="margin-right: 8px;cursor: pointer;font-size:16px;line-height:16px;color: var(--el-color-primary);">
				<el-tooltip
					effect="dark"
					content="新建分组"
					placement="top"
				>
					<el-icon  class="no-inherit" @click="handleOpenDialog('-1')"><FolderAdd /></el-icon>
				</el-tooltip>
			</div>
		</div>
		<div class="body">
			<div style="margin-bottom: 5px;">
				<el-input v-model="name" placeholder="名称" clearable>
				  <template #prefix>
				    <el-icon><Search /></el-icon>
				  </template>
				</el-input>
			</div>
			<el-scrollbar height="calc(100vh - 225px)">
				<el-tree
				ref="deptTreeRef"
				class="mt-2"
				:data="groupList"
				:expand-on-click-node="false"
				:filter-node-method="handleFilter"
				default-expand-all
				@node-click="handleNodeClick"
				:props="defaultProps"
				>
					<template #default="{ node, data }">
						<div class="custom-tree-node">
							<span>{{ node.label }}</span>
							<div style="padding-right: 5px;">
								<el-dropdown placement="bottom">
									<el-button icon="MoreFilled" size="small" link/>
									<template #dropdown>
										<el-dropdown-menu>
										  <el-dropdown-item icon="Edit" @click.stop="handleOpenDialog(data.id,data)">重命名</el-dropdown-item>
										  <el-dropdown-item icon="Delete" divided @click.stop="handleDelete(data)">删除</el-dropdown-item>
										</el-dropdown-menu>
									</template>
								</el-dropdown>
							</div>
						</div>
					</template>
				</el-tree>
			</el-scrollbar>
		</div>
		
		<!-- 表单弹窗 -->
		<el-dialog
		  v-model="dialog.visible"
		  :title="dialog.title"
		  width="500px"
		  :close-on-click-modal="false"
		  @close="handleCloseDialog"
		>
			<el-form ref="dbapiGroupFormRef" :model="formData" :rules="rules" label-width="100px">
				
				<el-form-item label="父级分组" prop="parentId">
				  <el-tree-select
				    v-model="formData.parentId"
				    placeholder="选择上级分组"
				    :data="options"
				    filterable
				    check-strictly
					:props="defaultProps"
				    :render-after-expand="false"
				  />
				</el-form-item>
				
				<el-form-item label="名称" prop="name">
				  <el-input v-model="formData.name" placeholder="请输入名称" />
				</el-form-item>
			
				<el-form-item label="排序" prop="sort">
				  <el-input-number
					v-model="formData.sort"
					controls-position="right"
					:min="0"
					style="width: 100px"
				  />
				</el-form-item>
			</el-form>
		
			<template #footer>
				<div class="dialog-footer">
				  <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
				  <el-button @click="handleCloseDialog" :loading="loading">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import DbapiAPI, { DbapiGroupForm } from "@/api/biz/dbapi";
const props = defineProps({
  modelValue: {
    type: [Number],
    default: undefined,
  },
});

import {
  recurOptions
} from "@/utils/TreeUtil";

const dbapiGroupFormRef = ref(ElForm);
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
const loading = ref(false);
const formData = reactive<DbapiGroupForm>({
  sort: 1,
});
const options = ref<any>([]);
const rules = reactive({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入标识", trigger: "blur" }],
});

const groupList = ref<any[]>(); // 部门列表
const deptTreeRef = ref(ElTree); // 部门树
const name = ref(); // 部门名称
const defaultProps = {
  children: 'children',
  label: 'name',
  value:'id',
  disabled:''
}
const emits = defineEmits(["node-click"]);
const deptId = useVModel(props, "modelValue", emits);

watchEffect(
  () => {
    deptTreeRef.value.filter(name.value);
  },
  {
    flush: "post", // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/**
 * 部门筛选
 */
function handleFilter(value: string, data: any) {
  if (!value) {
    return true;
  }
  return data.name.indexOf(value) !== -1;
}

/** 部门树节点 Click */
function handleNodeClick(data: { [key: string]: any }) {
  deptId.value = data.value;
  emits("node-click");
}

function handleOpenDialog(parentId?:string,row?: any) {
  dialog.visible = true;
  if (row) {
    dialog.title = "修改分组";
    Object.assign(formData, row);
  } else {
    dialog.title = "新增分组";
	Object.assign(formData, {
		parentId:parentId
	});
  }
}

function handleSubmit() {
  dbapiGroupFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        DbapiAPI.saveGroup({
			id:formData.id,
			parentId:formData.parentId,
			name:formData.name,
			sort:formData.sort,
		})
          .then(() => {
            ElMessage.success("修改成功");
			loadGroups();
            handleCloseDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        DbapiAPI.saveGroup({
			parentId:formData.parentId,
			name:formData.name,
			sort:formData.sort,
		})
          .then(() => {
            ElMessage.success("新增成功");
			loadGroups();
            handleCloseDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function handleDelete(data?: any) {
  ElMessageBox.confirm("确认删除"+data.name+"相关数据吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      DbapiAPI.deleteGroupByIds(data.id)
        .then(() => {
          ElMessage.success("删除成功");
          loadGroups();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  dbapiGroupFormRef.value.resetFields();
  dbapiGroupFormRef.value.clearValidate();
  formData.id = undefined;
  formData.name=undefined;
  formData.sort = 1;
}

const loadGroups=()=>{
	DbapiAPI.getGroups({}).then((data) => {
	  groupList.value = recurOptions(data,'-1');;
	  options.value = [{ id: "-1", name: "顶级菜单", children:groupList.value }];
	});
}

onBeforeMount(() => {
  loadGroups();
});

</script>
<style lang="scss" scoped>
	.custom-tree-node {
		height: 35px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}
</style>

